package com.fantabest.common.client.widget;

import java.util.List;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.store.StoreEvent;
import com.extjs.gxt.ui.client.store.StoreListener;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.FormPanel.LabelAlign;
import com.extjs.gxt.ui.client.widget.layout.HBoxLayout;
import com.extjs.gxt.ui.client.widget.layout.HBoxLayoutData;
import com.extjs.gxt.ui.client.widget.layout.BoxLayout.BoxLayoutPack;
import com.extjs.gxt.ui.client.widget.layout.HBoxLayout.HBoxLayoutAlign;
import com.fantabest.common.client.FantaBestConstants;
import com.fantabest.common.client.RegistryKeys;
import com.fantabest.common.client.StoreManager;

public class SeasonSelectionPanel extends LayoutContainer {

	private FantaBestConstants constants = Registry.get(RegistryKeys.CONSTANTS);
	private ComboBox<BeanModel> seasonCombo;
	private FormPanel panel;
	
	public SeasonSelectionPanel() {
		super();
		HBoxLayout layout = new HBoxLayout();
		layout.setHBoxLayoutAlign(HBoxLayoutAlign.TOP);
		layout.setPack(BoxLayoutPack.END);
		setLayout(layout);
		
		panel = new FormPanel();
		panel.setLabelAlign(LabelAlign.RIGHT);
		panel.setLabelWidth(50);
		panel.setHeaderVisible(false);
		panel.setWidth(210);
		panel.setFieldWidth(145);
		panel.setBodyBorder(false);
		
		seasonCombo = new ComboBox<BeanModel>();
		ListStore<BeanModel> store = StoreManager.getInstance().getSeasonStore();
		seasonCombo.setStore(store);
		seasonCombo.setFieldLabel(constants.season());
		seasonCombo.setDisplayField("title");
		seasonCombo.setEditable(false);
		seasonCombo.addSelectionChangedListener(new SelectionChangedListener<BeanModel>() {
			@Override
			public void selectionChanged(SelectionChangedEvent<BeanModel> se) {
				Registry.register(RegistryKeys.SEASON_ENTITY, se.getSelectedItem().getBean());
			}
		});
		
		
		store.addStoreListener(new StoreListener<BeanModel>() {
            @Override
            @SuppressWarnings("unchecked")
            public void storeDataChanged(StoreEvent<BeanModel> se) {
                super.storeDataChanged(se);
                List<BeanModel> beans = (List<BeanModel>) se.getStore().getModels();
                if (beans != null && beans.size() > 0) {
                	seasonCombo.setValue(beans.get(0));
                }
            }
            
        });
		
		store.getLoader().load();
		
		panel.add(seasonCombo);
		HBoxLayoutData data = new HBoxLayoutData(18, 3, 3, 3);
		this.add(panel,data);
	}
	
	public void setEnabledCombo(boolean enabled){
		seasonCombo.setEnabled(enabled);
	}

	
}
